<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<title>v-model</title>
		<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
		<script src="https://unpkg.com/vue@next"></script>
	</head>

	<body>
		<div id="watch-example">
		  <p>
		    输入一个问题，以 ? 号结尾输出答案:
		    <input v-model="question" />
		  </p>
		  <p>{{ answer }}</p>
		</div>  
	</body>
	<script>
		//view model
		const watchExampleVM = Vue.createApp({
		   data() {
		      return {
		         question: '',
		         answer: '每个问题结尾需要输入 ? 号。'
		      }
		   },
		   watch: {
		      // 每当问题改变时，此功能将运行，以 ? 号结尾
		      question(newQuestion, oldQuestion) {
		         if (newQuestion.indexOf('?') > -1) {
		            this.getAnswer()
		         }
		      }
		   },
		   methods: {
		      getAnswer() {
		         this.answer = '加载中...'
		         axios
		            .get('https://yesno.wtf/api')
		            .then(response => {
		            this.answer = response.data.answer
		         })
		            .catch(error => {
		            this.answer = '错误! 无法访问 API。 ' + error
		         })
		      }
		   }
		}).mount('#watch-example')
	</script>

</html>